package com.zhou.datapick;

import lombok.Data;

import java.util.*;

/**
 * @author lang.zhou
 * @since 2022/11/16
 */
@Data
public class JoinRelation {
    private DataKey leftKey;
    private String leftColumn;
    private DataKey rightKey;
    private String rightColumn;

    public static void main(String[] args) {
        JoinRelation r1 = new JoinRelation("A.value1=B.value2");
        JoinRelation r2 = new JoinRelation("B.value2=A.value1");
        Map<JoinRelation,Integer> map = new HashMap<>();
        map.put(r1,1);
        map.put(r2,2);
        System.out.println(r1.hashCode());
        System.out.println(r2.hashCode());
    }

    public JoinRelation() {

    }

    public JoinRelation(String leftName, String leftColumn,  String rightName, String rightColumn) {
        if(leftName.compareTo(rightName) < 0){
            this.leftKey = new DataKey(leftName);
            this.leftColumn = leftColumn;
            this.rightKey = new DataKey(rightName);
            this.rightColumn = rightColumn;
        }else if(leftName.compareTo(rightName) > 0){
            this.leftKey = new DataKey(rightName);
            this.leftColumn = rightColumn;
            this.rightKey = new DataKey(leftName);
            this.rightColumn = leftColumn;
        }else{
            throw new IllegalArgumentException("关联条件错误");
        }
    }


    public JoinRelation(String exp) {
        this(exp.split("=")[0].trim(), exp.split("=")[1].trim());
    }
    public JoinRelation(String left, String right) {
        this(left.split("\\.")[0].trim(),left.split("\\.")[1].trim(), right.split("\\.")[0].trim(), right.split("\\.")[1].trim());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        JoinRelation that = (JoinRelation) o;
        return Objects.equals(leftKey, that.leftKey) &&
                Objects.equals(leftColumn, that.leftColumn) &&
                Objects.equals(rightKey, that.rightKey) &&
                Objects.equals(rightColumn, that.rightColumn);
    }

    @Override
    public int hashCode() {
        List<String> l = new ArrayList<>(Arrays.asList(leftKey.toString(), leftColumn, rightKey.toString(), rightColumn));
        l.sort(String::compareTo);
        return Objects.hash(l.toArray());
    }
}